# -*- coding: utf-8 -*-
"""
Created on Fri Jul  3 02:44:49 2020

@author: Farman
"""


import ClassificationSamples.SampleMan as sampleman
import Landsat.LandsatFileListMan as landsatfilesman
import GeotiffMan
import joblib
import utm
import sys
import pathlib



def dump_path_row_dict_id_filename_data(path, row, dest_folder):
    '''
    '''
    print('\nProcessing path %3d row %3d'%(path, row), end = ' : ')

    file_name = 'P%03dR%03d-id_filename_data.joblib'%(path, row)
    file_name = pathlib.Path(dest_folder) / file_name

    if pathlib.Path(file_name).exists():
        print('already done. skip.')
        return
    
    print('')

    sample_man = sampleman.ClassificationSamples('/public/home/yule/code/team-w/ClassificationSamples/SamplesFromMrYu.joblib')
    landsat_man = landsatfilesman.LandsatFilesMan('/public/home/yule/code/team-w/WorkDir/landsat_files.joblib')
    dict_path_row_id = joblib.load('/public/home/yule/code/team-w/WorkDir/samples_path_row_id.joblib')

    def get_path_row_dict_id_filename_data(path, row):
        '''
        '''
        
        dict_id_filename_data = {} # final data to return

        dict_row_id = dict_path_row_id.get(path)

        if dict_row_id == None:
            print('    Now sample at path', path)
            return None

        ids = dict_row_id.get(row)

        if ids == None:
            print('    No sample at path %3d *row* %3d'%(path, row))
            return None
        
        ids = list(ids)
        ids.sort() # now got the sample id in current path, row.

        landsat_files = landsat_man.get_files_of_path_row(path, row)

        if landsat_files == None:
            print('    No landsat files at path %3d row %3d'%(path, row))
            return None

        # data reading of geotiff is heavy, so place it in outter loop.
        for landsat_file in landsat_files:
            print('    Reading file :', landsat_file)

            gtiff = GeotiffMan.GeoTiffMan(landsat_file)
            bands = None
            
            geo_tran = GeotiffMan.GeoTransform(gtiff.get_geo_transform())

            label_break = False

            for _id in ids:
                [lon, lat] = sample_man.get_pos_by_id(_id)
                #print('lon, lat:', lon, lat)
                
                # to utm coordinate : east, north
                east, north, *tail = utm.from_latlon(lat, lon)
                #print('utm east, north:', east, north)

                # to scene x, y
                [x, y] = geo_tran.get_reverse_project(east, north)
                #print('Scene x, y:', x, y)

                size_x, size_y = gtiff.get_size()

                if x < 0 or x >= size_x or y < 0 or y >= size_y:
                    print('        Position out of range : x %d  y %d'%(x,y), '| scene size :', size_x, size_y)
                    label_break = True
                    break

                if bands is None:
                    bands = gtiff.read_bands()
                #print(bands.shape) # band, rows, columns
                # now get the data of whole scene in current path, row

                data = bands[:, y, x]
                #print(len(data), ':', data)
                # now get the data of landsat scene of corresponding sample position

                # add info to dictionary
                dict_filename_data = dict_id_filename_data.get(_id)

                if dict_filename_data == None:
                    dict_filename_data = {}

                dict_filename_data.update({landsat_file : data})
                dict_id_filename_data.update({_id : dict_filename_data})                    

            if label_break:
                break

        return dict_id_filename_data
        
    data = get_path_row_dict_id_filename_data(path, row)

    if data is not None:
        joblib.dump(data, file_name)
    
    return


if __name__ == '__main__':
    if len(sys.argv) == 3:
        path = int(sys.argv[1])
        row  = int(sys.argv[2])
        dump_path_row_dict_id_filename_data(path, row, '/public/home/yule/code/team-w/WorkDir/path_row_sample/')
    else:
        print('Parameter need : path row')
        print('Usage:')
        print('=' * 30)
        print('    python LandsatSampleFetch.py [path] [row]')